#include "Player.h"
#include "raylib.h"
#include <fstream>
#include <iostream>
#include <string>
#include "PathManager.h"

Player::Player(float x, float y, const GameConfig& gameConfig) 
    : position{x, y}, 
      size{30.0f, 30.0f}, 
      velocityY(0), 
      config(gameConfig), 
      health(100),                           // 初始化血量为100
      onBreakableBoard(false),
      currentScore(0),
      highScore(0) {
    std::cout << "Player constructed at: x=" << x << ", y=" << y 
              << ", width=" << size.x << ", height=" << size.y << std::endl;
    
    // 加载历史最高分
    LoadHighScore();
}


void Player::Update() {
    // 处理左右移动
    if (IsKeyDown(KEY_LEFT)) {
        position.x -= config.playerMoveSpeed * GetFrameTime() * 60; // 校准到60FPS
    }
    if (IsKeyDown(KEY_RIGHT)) {
        position.x += config.playerMoveSpeed * GetFrameTime() * 60; // 校准到60FPS
    }
    
    // 应用重力影响（始终应用重力）
    velocityY += config.gravity * GetFrameTime() * 60; // 校准到60FPS
    
    // 更新位置
    position.y += velocityY * GetFrameTime() * 60; // 校准到60FPS
    
    // 如果玩家在可破坏板子上，持续减少血量
    
    // 增加分数（每秒1分）
    static double lastScoreTime = GetTime();
    double currentTime = GetTime();
    if (currentTime - lastScoreTime >= 1.0) {
        currentScore += 1;
        lastScoreTime = currentTime;
    }
    
    // 限制玩家在屏幕左右边界内
    if (position.x < 0) position.x = 0;
    if (position.x > config.screenWidth - size.x) position.x = config.screenWidth - size.x;
    
    // 调试输出玩家位置
    static int frameCount = 0;
    frameCount++;
    if (frameCount % 60 == 0) { // 每60帧输出一次
        std::cout << "Player position: (" << position.x << ", " << position.y << ")" << std::endl;
    }
}

void Player::HandleBreakableBoardCollision(float boardY) {
    // 当玩家落在可破坏板子上时，与普通板一样重置垂直速度
    if (velocityY > 0) {
        position.y = boardY - size.y;
        velocityY = 0; // 重置下落速度，让玩家能够再次跳跃
    }
    
    // 设置玩家在可破坏板子上
    onBreakableBoard = true;
}

// 处理尖刺板碰撞
void Player::HandleSpikyBoardCollision(float boardY) {
    // 玩家落在尖刺板上时，与普通板一样重置垂直速度
    if (velocityY > 0) {
        position.y = boardY - size.y;
        velocityY = 0; // 重置下落速度，让玩家能够再次跳跃
    }
    
    // 设置一个成员变量来跟踪上次减血时间
    static double lastHealthDecrease = 0;
    double currentTime = GetTime();
    // 每1秒减少1点血量
    if (currentTime - lastHealthDecrease >= 1.0) {
        health -= 1;
        lastHealthDecrease = currentTime;
    }
    
    // 不设置onBreakableBoard标志，因为这是独立的机制
}

void Player::Reset() {
    // 重置玩家位置到屏幕顶部
    position.x = config.screenWidth / 2;
    position.y = 100;
    
    // 重置玩家速度
    velocityY = 0;
    
    // 重置血量
    health = 100;
    onBreakableBoard = false;
    
    // 重置分数
    currentScore = 0;
    
    std::cout << "Player reset to: x=" << position.x << ", y=" << position.y << std::endl;
}

void Player::DecreaseHealth(int amount) {
    health -= amount;
    if (health < 0) health = 0;
}

void Player::SetOnBreakableBoard(bool onBreakable) {
    onBreakableBoard = onBreakable;
    // 移除了离开可破坏板子时重置计时器的逻辑
    // 因为lastHealthDecrease成员变量已被移除
}

bool Player::IsAlive() const {
    return health > 0;
}

void Player::HandleBoardCollision(float boardTopY) {
    // 玩家站在板子上时，将玩家位置调整到板子顶部
    position.y = boardTopY - size.y;
    
    // 重置下落速度，让玩家能够再次跳跃
    velocityY = 0;
    
    // 玩家站在普通板子上时，不再处于可破坏板子上
    onBreakableBoard = false;
}

void Player::IncreaseScore(int amount) {
    currentScore += amount;
}

void Player::SaveHighScore() {
    // 检查当前分数是否超过历史最高分
    if (currentScore > highScore) {
        highScore = currentScore;
        
        std::ofstream file(PathManager::GetHighScoreFilePath());
        if (file.is_open()) {
            file << highScore;
            file.close();
        }
    }
}

void Player::LoadHighScore() {
    std::ifstream file(PathManager::GetHighScoreFilePath());
    if (file.is_open()) {
        file >> highScore;
        file.close();
    } else {
        highScore = 0;
    }
}

void Player::Draw() {
    // 绘制玩家矩形（红色填充）
    DrawRectangle(position.x, position.y, size.x, size.y, RED);
    
    // 绘制玩家边框（黑色边框）
    DrawRectangleLines(position.x, position.y, size.x, size.y, BLACK);
    
    // 绘制UI（分数等）
    // 绘制当前分数
    std::string scoreText = "Score: " + std::to_string(currentScore);
    DrawText(scoreText.c_str(), 10, 10, 20, BLACK);
    
    // 绘制最高分
    std::string highScoreText = "High Score: " + std::to_string(highScore);
    DrawText(highScoreText.c_str(), 10, 35, 20, BLACK);
    
    // 绘制血量
    std::string healthText = "Health: " + std::to_string(health);
    DrawText(healthText.c_str(), 10, 60, 20, BLACK);
    
    // 绘制血量条
    DrawRectangle(10, 85, 100, 10, RED);  // 血量条背景
    DrawRectangle(10, 85, health, 10, GREEN);  // 当前血量
    DrawRectangleLines(10, 85, 100, 10, BLACK);  // 血量条边框
}